"""
PROJECT: dsocket
FILE: signals.py
AUTHOR: wensen
CREATE: 2022-02-17 
"""
from asgiref.sync import async_to_sync
from django.db.models.signals import post_save  # post_save 在某个Model保存之后调用
from django.dispatch import receiver
from mysite.models import Announcement
from channels.layers import get_channel_layer


# 将函数进行注册,声明为回调函数,第一个参数为信号类型,如果声明sender,
# 那么接收器只会接收这个sender的信号,这里声明为只接收Announcement模型的信号

# 对于每个唯一的dispatch_uid,接收器都只被信号调用一次

# 参数:**kwargs必须。第一个参数必须为sender, 当信号类型为 Model_signals, 接收到的第二个参数为模型对象.　　
@receiver(post_save, sender=Announcement, dispatch_uid="Announcement")
def announcement_post_save(sender, instance, **kwargs):
    # print(sender)  # 模型类
    # print(instance)  # 本条数据对象
    # print(kwargs)  # 额外参数
    message = {
        "type": "push_message",  # type 绑定的是推送消息的绑定方法
        "message": {
            "code": 2000,
            "data": {
                "promulgator": instance.promulgator.username,
                "title": instance.title,
                "content": instance.content,
            }
        }
    }
    channel_layer = get_channel_layer()
    # 异步在同步中使用，必须使用该方法包裹
    async_to_sync(channel_layer.group_send)(group="announcement", message=message)
